﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace TheOliver.Controls
{
    public class RemoveElementAction : System.Windows.Interactivity.TargetedTriggerAction<FrameworkElement>
    {
        #region Property to Expose
        [Category("Remove Element")]

        public string ElementName
        {
            get { return (string)GetValue(ElementNameProperty); }
            set { SetValue(ElementNameProperty, value); }
        }

        public static readonly DependencyProperty ElementNameProperty = DependencyProperty.Register("Element Name", typeof(string), typeof(RemoveElementAction), new PropertyMetadata(ElementNamePropertyPropertyChanged));

        #endregion

        protected override void Invoke(object o)
        {
            UserControl parent = Application.Current.RootVisual as UserControl;

            UIElement elementToRemove = parent.FindName(ElementName) as UIElement;

            if (elementToRemove != null)
            {
                try
                {

                    Panel parentOfElementToRemove = VisualTreeHelper.GetParent(elementToRemove) as Panel;
                    parentOfElementToRemove.Children.Remove(elementToRemove);
                } 
                catch (Exception e)
                {
                    string error = e.Message;
                    // More than likely, the parent was a UserControl
                }
            }
        }

        private static void ElementNamePropertyPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            // Do something
        }
    }
}
